<?php
namespace Sale\Model;

use Common\Model\CommonModel;

class CardSaleModel extends CommonModel {


    public function get_list($where = array(),$order = '',$from =  0,$to = 0){
        $list = M("CardSale")->alias("s")->field("s.*,l.logistics_name,c.number AS card_number,c.vip_name, c.vip_phone, c.vip_plate_number, sale.sale_name,u.user_nicename,u.user_phone,l.manager_id as l_m_id,s.sale_manager_id")->where($where)
            ->join("bdt_card c ON c.id = s.cid","LEFT")
            ->join("bdt_logistics l ON l.id = c.lid","LEFT")
            ->join("bdt_sale sale ON sale.id = s.sale_id","LEFT")
            ->join("bdt_users u ON u.id = s.uid","LEFT")
            ->order($order)
            ->limit($from , $to)
            ->select();
        return $list;
    }

    public function get_one($where = array(),$order = 's.create_time DESC'){
        $list = M("CardSale")->alias("s")->field("s.*,l.logistics_name,c.number AS card_number,c.vip_name, c.vip_phone, c.vip_plate_number, sale.sale_name,u.user_nicename,u.user_phone")->where($where)
            ->join("bdt_card c ON c.id = s.cid","LEFT")
            ->join("bdt_logistics l ON l.id = c.lid","LEFT")
            ->join("bdt_sale sale ON sale.id = s.sale_id","LEFT")
            ->join("bdt_users u ON u.id = s.uid","LEFT")
            ->order($order)
            ->find();
        return $list;
    }

    /**
     * 新增会员卡消费记录
     */
    public function insert_data($sale_id, $card_number, $goods_price, $good_num, $desc, $sale_good, $force_price, $uid=false){
        if(empty($sale_id)){
            return -6;
        }

        $good_unit_price = $sale_good['good_unit_price'];

        /*卡号不存在则返回失败*/
        $card = M("Card")->where(array("number"=>$card_number))->find();
        if(empty($card)){
            return -1;
        }else{
            $vip_logistics_ids = get_logistics_ids(1);
            $is_vip = in_array($card['lid'], explode(',', $vip_logistics_ids))?1:0;
            if ($is_vip) {
                $good_unit_price = $sale_good['vip_good_unit_price'];
            }else{
                $good_unit_price = $sale_good['good_unit_price'];
            }
        }
        if($card["status"] != 1){
            return -4;
        }

        /*金额预计算*/
        $return_data = $this->pre_clac($sale_id, $sale_good['id'], $goods_price, $good_num, $force_price, $card_number);
        if(!isset($return_data['price'])){
            return -3;
        }
        $price = $return_data['price'];

        $sale = M("Sale")->where(array("id"=>$sale_id))->find();
        //查询该消费机构的上级消费机构
        if($sale["sale_manager_id"]>0){
//            $sale_manager = M("SaleManager")->where(array('id'=>$sale["sale_manager_id"]))->find();
//            if($sale_manager["balance"]<$price){
//                return -3;
//            }
        }

        /*扣款余额不足则返回失败*/
        if($card['balance'] < $price){
            return -2;
        }

        /*计算*/
        $admin_card_sale_point = get_config_by_key('admin_card_sale_point');
        $logistics_card_sale_point = get_config_by_key('logistics_card_sale_point');
        $sale_point_line = $sale['point_line']; // 个人卡消费积分奖励线
        // 总积分
        $general_point = ceil($price/100 * $admin_card_sale_point);
        // 自营积分
        $self_point = ceil($price/100 * $logistics_card_sale_point);
        // 个人卡消费机构奖励积分
        if ($sale_point_line > 0 && $card['lid'] == 1) {
            $general_point += floor($price / $sale_point_line);
        }
        // 应得积分
        $point = $general_point + $self_point;

        // 卡内余额
        $plus_price = round($card['balance']-$price,2);
        // 卡内积分
        $plus_point = $card['use_point']+$point;
        $card_point = $card['point']+$point;

        // 消费时间
        $create_time = time();
        // 操作者
        $uid = $uid?$uid:session('ADMIN_ID');
        // 订单号
        $number = date("YmdHis").rand(10000,99999);

        /*插入数组*/
        $insert = array();
        
        $insert['desc'] = $desc;
        $insert['uid'] = $uid;
        $insert['number'] = $number;
        $insert['create_time'] = $create_time;

        $insert['sale_id']          = $sale['id'];
        $insert["sale_price"]       = $sale["price"];
        $insert["sale_manager_id"]  = $sale["sale_manager_id"];

        $insert['cid']          = $card['id'];
        $insert['lid']          = $card['lid'];
        $insert['card_number']  = $card['number'];
        
        $insert['price']                = $return_data['price'];
        $insert['dis_price']            = $return_data['dis_price'];
        $insert['admin_oil_discount']   = $return_data['admin_oil_discount'];
        $insert['goods_num']            = $return_data['good_num'];
        $insert['goods_price']          = $return_data['goods_price'];
        
        $insert['goods_name']       = $sale_good['good_name'];
        $insert['goods_unit_price'] = $good_unit_price;
        $insert['goods_unit']       = $sale_good['good_unit'];
        $insert['is_oil']           = $sale_good['is_oil'];

        $insert['general_point']    = $general_point;
        $insert['self_point']       = $self_point;
        $insert['plus_point']       = $plus_point;
        $insert['plus_price']       = $plus_price;

        $result = $this->add($insert);
        if($result){    //消费成功 扣除卡金额
            M("Card")->where(array("id"=>$card['id']))->save(
                array(
                    "balance"=>$plus_price,
                    "point"=>$card_point,
                    "use_point"=>$plus_point,
                    'last_sale_time'=>$create_time
                )
            );
            M("Sale")->where(array("id"=>$sale['id']))->save(array("price"=>$sale['price']+$price));
            if($sale["sale_manager_id"]>0){
                M("SaleManager")->where(array('id'=>$sale["sale_manager_id"]))->setDec('balance',$price);
            }
        }
        return $result;
    }

    /**
     * 消费金额预计算
     * @param $sale_id 消费机构id
     * @param $good_id 选择商品id
     * @param $preprice 设定的预售价
     * @param $good_num 设定的商品数量
     * @param $last_key 计算方式 [preprice|good_num]
     *
     *
    */
    public function pre_clac($sale_id, $good_id, $goods_price, $good_num, $last_key = 'preprice',$card_number = null){
        $sale = M("Sale")->where(array("id"=>$sale_id))->find();
        $sale_good = M("SaleGood")->where(array("id"=>$good_id))->find();

        $good_unit_price = $sale_good['good_unit_price'];
        /*vip价格判断*/
        if ($card_number == 'is_vip') {
            $good_unit_price = $sale_good['vip_good_unit_price'];
        }elseif ($card_number) {
            $card = M("Card")->where(array("number"=>$card_number))->find();
            $person_lids = get_logistics_ids(1);
            if ($card && in_array($card['lid'],explode(',', $person_lids))) {
                $good_unit_price = $sale_good['vip_good_unit_price'];
            }
        }

        if (!$good_id) {
            return -5;
        }

        $admin_oil_discount = get_config_by_key('admin_oil_discount');

        if ($good_num && $last_key == 'good_num') {

            $goods_price = round($good_unit_price * $good_num,2);
            $good_name = $sale_good['good_name'];
            $is_oil = $sale_good['is_oil'];

            /*如果是石油就计算优惠*/
            $disprice = 0;
            if ($is_oil == 1) {
                $disprice = round($admin_oil_discount * $good_num,2);
            }

            $price = round($goods_price - $disprice,2);

        }elseif ($goods_price) {
            $good_name = $sale_good['good_name'];
            $is_oil = $sale_good['is_oil'];

            /*如果是石油就计算优惠*/
            $disprice = 0;
            if ($is_oil == 1) {
                $per_good_price = $good_unit_price - $admin_oil_discount;
            }else{
                $per_good_price = $good_unit_price;
            }

            $good_num = round( $goods_price / $per_good_price, 2);
            if ($is_oil == 1) {
                $disprice = round( $admin_oil_discount * $good_num, 2);
            }

            $price = $goods_price - $disprice;

        }

        //查询该消费机构的上级消费机构
        if($sale["sale_manager_id"]>0){
//            $sale_manager = M("SaleManager")->where(array('id'=>$sale["sale_manager_id"]))->find();
//            if($sale_manager["balance"] < $price){
//                return -4;
//            }
        }

        $data['good_num'] = $good_num;
        $data['dis_price'] = $disprice;
        $data['price'] = $price;
        $data['goods_price'] = $goods_price;
        $data['good_id'] = $sale_good['id'];
        $data['last_key'] = $last_key;
        $data['admin_oil_discount'] = $admin_oil_discount;

        return $data;
    }

    /**
     * 删除记录
     */
    public function delete_data($id){
        $uid = session('ADMIN_ID');
        $user = M("Users")->where(array("id"=>session('ADMIN_ID')))->find();

        $card_sale = $this->where(array('id'=>$id))->find();
        if (empty($card_sale)) {
            return -1;
        }
        $card_sale_cancel = $card_sale;
        unset($card_sale_cancel['id']);
        $card_sale_cancel['card_sale_id'] = $card_sale['id'];
        $card_sale_cancel['admin_id'] = $uid;
        $card_sale_cancel['admin_name'] = $user['user_nicename'];
        $card_sale_cancel['admin_model'] = $user['model'];
        $card_sale_cancel['operation_time'] = time();

        /*卡号不存在则返回失败*/
        $card = M("Card")->where(array("number"=>$card_sale['card_number']))->find();
        if(empty($card)){
            return -2;
        }

        /*计算*/
        // 卡内余额
        $plus_price = round($card['balance'] + $card_sale['price'],2);

        // 应扣积分
        $mins_point = $card['general_point'] + $card_sale['self_point'];
        // 卡内积分
        $card_point = $card['point'] - $mins_point;
        $plus_point = $card['use_point'] - $mins_point;

        $result = $this->delete($id);
        M("CardSaleCancel")->add($card_sale_cancel);

        if($result){    //消费成功 扣除卡金额
            M("Card")->where(array("id"=>$card['id']))->save(
                array(
                    "balance"=>$plus_price,
                    "point"=>$card_point,
                    "use_point"=>$plus_point,
                )
            );
            $sale = M("Sale")->where(array("id"=>$card_sale['sale_id']))->find();
            M("Sale")->where(array("id"=>$card_sale['sale_id']))->save(array("price" => $sale['price'] - $card_sale['price']));

            //查询该消费机构的上级消费机构
            if($card_sale["sale_manager_id"] > 0){
//                $sale_manager = M("SaleManager")->where(array('id'=>$card_sale["sale_manager_id"]))->find();
//                $new_manager_balance = $sale_manager["balance"] + $card_sale['price'];
                M("SaleManager")->where(array('id'=>$card_sale["sale_manager_id"]))->setInc('balance', $card_sale['price']);
            }
        }
        return $result;
    }
}